package com.apache.poi.word.controller;

import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STOnOff;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.math.BigInteger;
import java.util.List;

/**
 * @Author: HUANG GY.
 * @Date: 2022/2/7 14:10
 * @Description: com.apache.poi.word.controller
 */
@RestController
public class NetController {

    public static void write2Docx()throws Exception{
        XWPFDocument document= new XWPFDocument();

        //Write the Document in file system
        FileOutputStream out = new FileOutputStream(new File("/Users/huangguoye/IdeaProjects/gitee/word/word-demo/src/main/resources/docs/create_table.docx"));

        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleParagraphRun = titleParagraph.createRun();

        titleParagraphRun.setText("Java PoI");
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontSize(20);

        //段落
        XWPFParagraph firstParagraph = document.createParagraph();
        XWPFRun run = firstParagraph.createRun();
        run.setText("Java POI 生成word文件。");
        run.setColor("696969");
        run.setFontSize(16);

        //设置段落背景颜色
        CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
        cTShd.setVal(STShd.CLEAR);
        cTShd.setFill("97FFFF");

        //换行
        XWPFParagraph paragraph1 = document.createParagraph();
        XWPFRun paragraphRun1 = paragraph1.createRun();
        paragraphRun1.setText("\r");

        //基本信息表格
        XWPFTable infoTable = document.createTable();
        //去表格边框
        infoTable.getCTTbl().getTblPr().unsetTblBorders();

        //列宽自动分割
        CTTblWidth infoTableWidth = infoTable.getCTTbl().addNewTblPr().addNewTblW();
        infoTableWidth.setType(STTblWidth.DXA);
        infoTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行
        XWPFTableRow infoTableRowOne = infoTable.getRow(0);
        infoTableRowOne.getCell(0).setText("职位");
        infoTableRowOne.addNewTableCell().setText(": Java 开发工程师");

        //表格第二行
        XWPFTableRow infoTableRowTwo = infoTable.createRow();
        infoTableRowTwo.getCell(0).setText("姓名");
        infoTableRowTwo.getCell(1).setText(": seawater");

        //表格第三行
        XWPFTableRow infoTableRowThree = infoTable.createRow();
        infoTableRowThree.getCell(0).setText("生日");
        infoTableRowThree.getCell(1).setText(": xxx-xx-xx");

        //表格第四行
        XWPFTableRow infoTableRowFour = infoTable.createRow();
        infoTableRowFour.getCell(0).setText("性别");
        infoTableRowFour.getCell(1).setText(": 男");

        //表格第五行
        XWPFTableRow infoTableRowFive = infoTable.createRow();
        infoTableRowFive.getCell(0).setText("现居地");
        infoTableRowFive.getCell(1).setText(": xx");



        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);
        //添加页眉
        CTP ctpHeader = CTP.Factory.newInstance();
        CTR ctrHeader = ctpHeader.addNewR();
        CTText ctHeader = ctrHeader.addNewT();
        String headerText = "ctpHeader";
        ctHeader.setStringValue(headerText);
        XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
        //设置为右对齐
        headerParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFParagraph[] parsHeader = new XWPFParagraph[1];
        parsHeader[0] = headerParagraph;
        policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);

        //添加页脚
        CTP ctpFooter = CTP.Factory.newInstance();
        CTR ctrFooter = ctpFooter.addNewR();
        CTText ctFooter = ctrFooter.addNewT();
        String footerText = "ctpFooter";
        ctFooter.setStringValue(footerText);
        XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
        headerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFParagraph[] parsFooter = new XWPFParagraph[1];
        parsFooter[0] = footerParagraph;
        policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);

        document.write(out);
        out.close();
    }

    public static void writeTOC() throws Exception {
        XWPFDocument document= new XWPFDocument();
        //Write the Document in file system
        FileOutputStream out = new FileOutputStream(new File("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\create_toc.docx"));
        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText("Java PoI");
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontSize(20);
        //段落
        XWPFParagraph firstParagraph = document.createParagraph();
        firstParagraph.setStyle("Heading1");
        XWPFRun run = firstParagraph.createRun();
        run.setText("段落1段落1");
        run.setColor("696969");
        run.setFontSize(18);
        //段落
        XWPFParagraph firstParagraph1 = document.createParagraph();
        firstParagraph1.setStyle("Heading1");
        XWPFRun run1 = firstParagraph1.createRun();
        run1.setText("段落2段落2");
        run1.setColor("696969");
        run1.setFontSize(18);
        document.createTOC();
        document.write(out);
        out.close();
    }

    public static void writeTOC2() throws Exception {
        XWPFDocument doc = new XWPFDocument(new FileInputStream("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\若依环境使用手册.docx"));

        String [] numArr = new String[100];
        for (int i = 0; i < 100; i++) {
            numArr[i] = String.valueOf(i);
        }

        List<XWPFParagraph> paragraphs = doc.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            String text = paragraph.getText();
            if (text != null) {
                int index = text.indexOf(".");
                if (text.indexOf(".")>0) {
                    int dolNum = 0 ;
                    for (int i = 0; i < text.length(); i++) {
                        if (text.charAt(i) == '.') {
                            dolNum++ ;
                        }
                    }
                    if (dolNum!=1) {
                        continue;
                    }
                    String numStr = text.substring(0, index);
                    for (String temp : numArr) {
                        if (numStr.equals(temp)) {
                            paragraph.setStyle("Heading1");
                            System.out.println("text="+text);
                            break;
                        }
                    }
                }
            }

        }
        doc.createTOC();
        FileOutputStream out = new FileOutputStream("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\若依环境使用手册002.docx");
        doc.write(out);
        out.close();
    }


    public static void writeTOC3() throws Exception {
        XWPFDocument doc = new XWPFDocument(new FileInputStream("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\秩序册.docx"));
        List<XWPFParagraph> paragraphs = doc.getParagraphs();
        int size1 = paragraphs.size();
        XWPFParagraph paragraphMl = null ;
        for (XWPFParagraph paragraph : paragraphs) {
            String text = paragraph.getText();
            if ("目录".equals(text)) {
                paragraphMl = paragraph ;
            }

            if (null==text || "".equals(text) || "\n".equals(text)) {
                continue;
            }
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String fontName = run.getFontName();
                String fontFamily = run.getFontFamily();
                String color = run.getColor();
                Double fontSizeAsDouble = run.getFontSizeAsDouble();
                boolean bold = run.isBold();
                boolean flag = "仿宋_GB2312".equals(fontName) && 18.0==fontSizeAsDouble &&  "000000".equals(color) && bold == true ;
                if (flag) {
                    paragraph.setStyle("Heading1");
                    break;
                }

            }

        }
        doc.createTOC();
        int size = doc.getParagraphs().size();
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            String text = paragraph.getText();
            System.out.println("texttexttexttexttext===="+text);
            if ("Table of Contents".equals(text)) {
                System.out.println(text);
            }
        }
        FileOutputStream out = new FileOutputStream("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\秩序册001.docx");
        doc.write(out);
        out.close();
    }

    public static void generateTOC() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\秩序册.docx");
        XWPFDocument doc = new XWPFDocument(fileInputStream);
        String findText = "toc";
        String replaceText = "";
        for (XWPFParagraph p : doc.getParagraphs()) {
            for (XWPFRun r : p.getRuns()) {
                int pos = r.getTextPosition();
                String text = r.getText(pos);
                System.out.println(text);
                if (text != null && text.contains(findText)) {
                    text = text.replace(findText, replaceText);
                    r.setText(text, 0);
                    addField(p, "TOC \\o \"1-3\" \\h \\z \\u");
//                    addField(p, "TOC \\h");
                    break;
                }
            }
        }
        OutputStream out = new FileOutputStream("D:\\05_code\\gitee\\word-demo\\src\\main\\resources\\docs\\秩序册002.docx");
        doc.write(out);
        out.close();
    }

    private static void addField(XWPFParagraph paragraph, String fieldName) {
        CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
        ctSimpleField.setInstr(fieldName);
        ctSimpleField.setDirty(true);
        ctSimpleField.addNewR().addNewT().setStringValue("<<fieldName>>");
    }



    public static void main(String[] args) throws Exception {
//        write2Docx();
//        writeTOC();
//        writeTOC2();
//        writeTOC3();
//        generateTOC();
        write2Docx();
    }


}
